package com.uduemc.biso.node.web.api.controller;

import java.io.IOException;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.web.api.dto.RequestRedirectUrl;
import com.uduemc.biso.node.web.api.pojo.ResponseRedirectUrl;
import com.uduemc.biso.node.web.api.service.RedirectUrlService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/api/host-redirect-url")
@Api(tags = "链接重定向模块")
@Slf4j
public class HostRedirectUrlController {

	@Autowired
	private RedirectUrlService redirectUrlServiceImpl;

	@PostMapping("/list")
	@ApiOperation(value = "获取链接重定向数据", notes = "列表的方式返回链接重定向的数据", response = ResponseRedirectUrl.class)
	public JsonResult list() throws IOException {
		return redirectUrlServiceImpl.findListByHostIdAndIfNot404Create();
	}

	@PostMapping("/save")
	@ApiOperation(value = "保存链接重定向数据", notes = "通过主键ID，新增id不用传值，修改id需要传值。列表的方式返回链接重定向的数据", response = ResponseRedirectUrl.class)
	public JsonResult save(@Valid @RequestBody RequestRedirectUrl requestRedirectUrl, BindingResult errors) throws IOException {
		if (errors.hasErrors()) {
			for (FieldError fieldError : errors.getFieldErrors()) {
				String defaultMessage = fieldError.getDefaultMessage();
				String field = fieldError.getField();
				log.info("field: " + field + " defaultMessage: " + defaultMessage);
				return JsonResult.messageError(defaultMessage);
			}
		}

		return redirectUrlServiceImpl.save(requestRedirectUrl);
	}

	@PostMapping("/delete")
	@ApiOperation(value = "删除链接重定向数据", notes = "通过主键ID，删除链接重定向数据。返回被删除的链接重定向数据", response = ResponseRedirectUrl.class)
	public JsonResult delete(@RequestParam("id") long id) throws IOException {
		return redirectUrlServiceImpl.delete(id);
	}
}
